import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'package:flutter_blue/flutter_blue.dart';
import 'GlobalSeer.dart';

class MyBlues{

  FlutterBlue flutterBlue = FlutterBlue.instance;
  late BluetoothDevice bleDevice;
  late BluetoothCharacteristic readWriteChar;

  void startScan() async{
    var subscription = flutterBlue.scanResults.listen((results) {

      if(results.isNotEmpty){
        for(ScanResult item in results) {
          print("advName:"+item.device.name);
        }
      }
    },
      onError:(e){
        print("onError:"+e.toString());
      },
    );

    flutterBlue.startScan(timeout: Duration(seconds: 5)).then((value) {
      List<Widget> items=[];
      for(ScanResult res in value){
        items.add(ListTile(
          title:Text("name:"+res.device.name) ,
          onTap: (){
            GlobalSeer.dispatchEvent("onDialogDone",res.device);
            Get.back();
          },
        ));
      }
      print("startScan: value:"+value.toString());
      Get.defaultDialog(
        title: "BLES",
        content: Column(children: items,),
      );
      //Get.snackbar("scan done", "scan is done!");
      flutterBlue.stopScan();
    });
  }

  void connectDevice(BluetoothDevice device){
    bleDevice=device;
    bleDevice.connect().then((value){
      print("成功连接！");
      bleDevice.discoverServices().then((List<BluetoothService> services) {
        for(BluetoothService service in services){
          print(service.uuid.toString());
          //匹配服务端service的uuid
          if (service.uuid.toString() == "b408e1a0-3d8a-11ed-b878-0242ac120002") {
            readWriteChars(service);
          }
        }
      });
    });
  }

  void readWriteChars(BluetoothService service){
    List<BluetoothCharacteristic> characteristics = service.characteristics;
    for (BluetoothCharacteristic characteristic in characteristics) {
      var valuex = characteristic.uuid.toString();
      print("所有特征值 --- $valuex");
      //匹配服务端characteristic的uuid
      if(characteristic.uuid.toString() == "de045162-3d97-11ed-b878-0242ac120002") {
        print("匹配到正确的特征值");
        readWriteChar = characteristic;

        Timer(const Duration(seconds: 6), (){
          readWriteChar.write(utf8.encode("abc123"));
        });
        Timer(const Duration(seconds: 5), (){
          loopReceiveData();
        });
      }
    }
  }

  void loopReceiveData() async{
    await readWriteChar.setNotifyValue(true);
    readWriteChar.value.listen((value) {
      if (value == null) {
        print("我是蓝牙返回数据 - 空！！");
        return;
      }
      print("我是蓝牙返回数据:${utf8.decode(value)}");
    });
  }

  void sendData(List<int> data){
    readWriteChar.write(data);
  }

  void disconnectDevice(){
    bleDevice.disconnect();
  }

}

main(){
  runApp(TheApp());
}

class TheApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(home: MyHome(),);
  }
}

class MyHome extends StatelessWidget{

  MyBlues blues=MyBlues();

  @override
  Widget build(BuildContext context){

    GlobalSeer.addEventListener("onDialogDone", (BluetoothDevice device){
      print("device.id:"+device.id.toString());
      blues.connectDevice(device);
    });

    return Scaffold(
      appBar: AppBar(title:const Text("BLE"),centerTitle: true,backgroundColor: Colors.purple,),
      body:Center(
        child:Column(
          children:[
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              blues.startScan();
            }, child: const Text("SCAN")),
            const SizedBox(height: 50,),
            Text("deciceName:"),
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              GlobalSeer.removeEventListener("onDialogDone");
            }, child: const Text("Remove")),
          ],
        ) ,
      ),

    );
  }

}